#include "clib_thrd.h"
#include <stdlib.h>
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <sched.h>



static i32_t thrd_fun(void* args) {
    cpu_set_t cpumask;
    clib_thrd_t *thrd = args;
    thrd->tid = thrd_current();

    clib_spinlock_init(thrd->lock);
    
    if(thrd->cpu != -1) {
        CPU_ZERO(&cpumask);
        CPU_SET(thrd->cpu, &cpumask);
        /** 绑定cpu **/
        sched_setaffinity(0, sizeof(cpumask), &cpumask);
    }
    /** TODO设置内存分配策略 **/
    if(thrd->node != -1) {

    }

    while (thrd->start)
    {
        if(thrd->statue == 1) {
            if(thrd->work) {
                thrd->work(thrd->args);

                thrd->work = NULL;
                thrd->args = NULL;
                thrd->statue = 2;
            }
        } else if(thrd->statue == 2) {
            /** todo sleep **/
        }
    }
    return 0;
}

i32_t clib_thrd_init(clib_thrd_t *thrd) 
{
    i32_t ret;
    if(!thrd) {
        return -1;
    }
    ret = thrd_create(&thrd->tid, thrd_fun, thrd);

    if(ret != thrd_success) {
        return -1;
    }
    return 0;
}

i32_t clib_thrd_join(clib_thrd_t *thrd)
{
    if(!thrd) {
        return -1;
    }
    return thrd_join(&thrd->tid, NULL);
}